const { findLoanByLimitAndFields, countLoanByFields, findLoanById, updateLoanByfields } = require('../models/loan.js')
const { mkPager } = require('../utils')
const { APPROVE } = require('./config.js')
const { stateFlow, waitingStatus } = require('./approveHelper.js')

exports.list = function (isFirst) {
  return async ctx => {
    // 获取参数 pageNo pageSize name？
    const { pageNo, pageSize, name } = ctx.query;
    // 查询数据 初审1  终审4  status
    const status = isFirst ? 1 : 4
    const { start, size } = mkPager(pageNo, pageSize)
    if (name) {
      var res = await findLoanByLimitAndFields(start, size, { name, status })
      var count = await countLoanByFields({ name, status })
    } else {
      var res = await findLoanByLimitAndFields(start, size, { status })
      var count = await countLoanByFields({ status })
    }
    // 返回数据
    const rows = count[0].rows  // 共有多少条
    const pages = Math.ceil(rows / size)   // 共有多少页
    ctx.success({
      data: {
        data: res
      },
      rows,
      pages
    })
  }
}

exports.list.first = exports.list(true)
exports.list.end = exports.list(false)

exports.doApprove = function (isPass) {
  return async ctx => {
    // 检查当前角色是否可以审批
    const { type }  = ctx.state.user;
    if (type !== APPROVE) {
      return ctx.fail('当前登录用户无权限审批！')
    }
    // 获取路由参数
    const { loanId } = ctx.request.body;
    const loanRes = await findLoanById(loanId);
    if (loanRes.length === 0) {
      return ctx.fail('当前申请不存在！')
    }
    const originStatus = loanRes[0].status;
    if (!waitingStatus.includes(originStatus)) {
      return ctx.fail(`当前状态无法申请${isPass ? '通过': '拒绝'}`)
    }
    const currentStatus = stateFlow[originStatus][isPass ? 'pass' : 'reject']
    if (currentStatus.v == originStatus) {
      return ctx.fail('申请状态未改变！')
    }
    // 更新数据库状态
    const updateRes = await updateLoanByfields({ status: currentStatus.v }, loanId);
    if (updateRes.changedRows === 0) {
      return ctx.fail('更新状态失败！')
    }
    return ctx.success({
      info: '更新状态成功',
      from: originStatus,
      to: currentStatus.v
    })
  }
}

exports.approve = {
  first: {},
  end: {}
}

exports.approve.first.pass = exports.approve.end.pass = exports.doApprove(true)
exports.approve.first.reject = exports.approve.end.reject = exports.doApprove(false)